<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    // 压缩图片
    function compress(base64String, w, quality){
      // var getMimeType = function(urlData) {
      //   var arr = urlData.split(",");
      //   var mime = arr[0].match(/:(.*?);/)[1];
      //   // return mime.replace("image/", "");
      //   return mime;
      // };
      var newImage = new Image();
      var imgWidth, imgHeight;

      var promise = new Promise(resolve => (newImage.onload = resolve));
      newImage.src = base64String;
      return promise.then(() => {
        imgWidth = newImage.width;
        imgHeight = newImage.height;
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        if (Math.max(imgWidth, imgHeight) > w) {
          if (imgWidth > imgHeight) {
            canvas.width = w;
            canvas.height = (w * imgHeight) / imgWidth;
          } else {
            canvas.height = w;
            canvas.width = (w * imgWidth) / imgHeight;
          }
        } else {
          canvas.width = imgWidth;
          canvas.height = imgHeight;
        }
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(newImage, 0, 0, canvas.width, canvas.height);
        // var base64 = canvas.toDataURL(getMimeType(base64String), quality);
        var base64 = canvas.toDataURL("image/jpeg", quality);
        console.log(base64);
        return base64;
      });
    }

    
  </script>
</body>
</html>